import '../../core/auth/auth_service.dart';
import '../../core/base/base_view_model.dart';
import '../../core/http/http_client.dart';

class DashboardViewModel extends BaseViewModel {
  final _httpClient = HttpClient();

  // 统计数据
  int totalOrders = 0;
  int todayOrders = 0;
  int totalProducts = 0;
  int totalUsers = 0;

  DashboardViewModel() {
    loadDashboardData();
  }

  Future<void> loadDashboardData() async {
    try {
      setBusy(true);
      
      // 获取仪表盘数据
      final response = await _httpClient.get('/dashboard/stats');
      
      if (response.code == 200) {
        final data = response.data;
        totalOrders = data['totalOrders'] ?? 0;
        todayOrders = data['todayOrders'] ?? 0;
        totalProducts = data['totalProducts'] ?? 0;
        totalUsers = data['totalUsers'] ?? 0;
        notifyListeners();
      } else {
        setError('获取仪表盘数据失败');
      }
    } catch (e) {
      setError('加载数据失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  Future<void> refresh() async {
    await loadDashboardData();
  }

  Future<void> logout() async {
    try {
      setBusy(true);
      await AuthService().logout();
      notifyListeners();
    } catch (e) {
      setError('退出登录失败：${e.toString()}');
      rethrow;
    } finally {
      setBusy(false);
    }
  }
}